package cn.dada.dadarecipes.community.article.service.impl;


import cn.dada.dadarecipes.base.enums.ArticleAuditStatusEnum;
import cn.dada.dadarecipes.base.enums.ArticleStatusEnum;
import cn.dada.dadarecipes.base.exception.ServiceException;
import cn.dada.dadarecipes.base.response.StatusCode;
//import cn.dada.dadarecipes.base.util.LoginValidation;
import cn.dada.dadarecipes.community.article.mapper.ArticleDetailsMapper;
import cn.dada.dadarecipes.community.article.mapper.ArticleMapper;
import cn.dada.dadarecipes.community.article.pojo.dto.ArticleQuery;
import cn.dada.dadarecipes.community.article.pojo.dto.ArticleSaveParam;
import cn.dada.dadarecipes.community.article.pojo.entity.Article;
import cn.dada.dadarecipes.community.article.pojo.entity.ArticleDetails;
import cn.dada.dadarecipes.community.article.pojo.vo.ArticleDetailsVO;
import cn.dada.dadarecipes.community.article.pojo.vo.ArticleVO;
import cn.dada.dadarecipes.community.article.pojo.vo.MyArticleVO;
import cn.dada.dadarecipes.community.article.service.ArticleService;
import cn.dada.dadarecipes.community.audit.mapper.AuditMapper;
import cn.dada.dadarecipes.community.audit.pojo.dto.AuditInsertParam;
import cn.dada.dadarecipes.community.favorites.mapper.FavoritesMapper;
import cn.dada.dadarecipes.community.favorites.pojo.dto.FavoritesSaveParam;
import cn.dada.dadarecipes.community.thumbsup.mapper.ThumbsUpMapper;
import cn.dada.dadarecipes.community.thumbsup.pojo.entity.ThumbsUp;
import cn.dada.dadarecipes.user.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleDetailsMapper articleDetailsMapper;
    @Autowired
    private FavoritesMapper favoritesMapper;
    @Autowired
    private ThumbsUpMapper thumbsUpMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuditMapper auditMapper;


    /**
     * 业务层-我的文章查询
     * @param userId
     * @param session
     * @return
     */
    @Override
    public List<MyArticleVO> selectMyArticle(Long userId, HttpSession session) {
        log.debug("业务层-我的文章查询: userId={}", userId);
        /* 用户是否登录校验 */
//        LoginValidation.isMyselfLogin(userId,session);

        Article article = new Article();
        List<Long> userIds = Collections.singletonList(userId);
        article.setUserIds(userIds);
        List<ArticleVO> vos = articleMapper.selectArticle(article);
        List<MyArticleVO> list = null;
        if (!vos.isEmpty()) {
            list = vos.stream().map(vo->{
                MyArticleVO myArticleVO = new MyArticleVO();
                BeanUtils.copyProperties(vo, myArticleVO);
                return myArticleVO;
            }).collect(Collectors.toList());
        }
        return list;
    }


    /**
     * 业务层-我的收藏文章查询
     * @param userId
     * @param session
     * @return
     */
    @Override
    public List<MyArticleVO> selectLikeArticle(Long userId, HttpSession session) {
        log.debug("业务层-我的收藏文章查询: userId={}", userId);
        /* 用户是否登录校验 */
//        LoginValidation.isMyselfLogin(userId,session);

        List<MyArticleVO> myArticleVOS = favoritesMapper.selectLikeArticle(userId);
        log.debug("业务层-我的收藏文章查询-查询结果数:{}", myArticleVOS);
        return myArticleVOS;
    }


    /**
     * 业务层-我的点赞文章查询
     * @param userId
     * @param session
     * @return
     */
    @Override
    public List<MyArticleVO> selectApproveArticle(Long userId, HttpSession session) {
        log.debug("业务层-我的点赞文章查询: userId={}", userId);
        /* 用户是否登录校验 */
//        LoginValidation.isMyselfLogin(userId,session);

        return thumbsUpMapper.selectApproveArticle(userId);
    }


    /**
     * 业务层-首页文章查询
     * @param articleQuery
     * @return List<ArticleVO>
     */
    @Override
    public List<ArticleVO> selectArticle(ArticleQuery articleQuery) {
        log.debug("业务层-首页文章查询: articleQuery={}", articleQuery);
        Article article = new Article();
        BeanUtils.copyProperties(articleQuery, article);

        /* 根据用户名模糊查询用户id集合 */
        List<Long> userIds = null;
        userIds = FuzzyQueryThroughUsername(article, userIds);

        /* 查询文章状态为通过审核且所有人可见文章列表 */
        return getArticleList(article, userIds);
    }
    /**
     * 根据用户名模糊查询用户id集合
     * @param article
     * @param userIds
     * @return List<Long>
     */
    private List<Long> FuzzyQueryThroughUsername(Article article, List<Long> userIds) {
        String username = article.getUsername();
        if (username != null && !username.trim().isEmpty()) {
            userIds = userMapper.selectUserIdByUserName(username);
            // 判断用户id集合是否为空，即根据用户名查询用户是否存在
            if (userIds.isEmpty()) throw new ServiceException(StatusCode.USER_NOT_EXIST);//用户不存在
        }
        return userIds;
    }
    /**
     * 查询文章状态为通过审核且所有人可见文章列表
     * @param article
     * @param userIds
     * @return List<ArticleVO>
     */
    private List<ArticleVO> getArticleList(Article article, List<Long> userIds) {
        article.setUserIds(userIds);//设置查询用户id集合
        article.setAuditStatus(ArticleAuditStatusEnum.AUDIT_PASS.getCode());//文章审核通过
        article.setArticleStatus(ArticleStatusEnum.VISIBLE_TO_EVERYONE.getCode());//文章所有人可见
        List<ArticleVO> list = articleMapper.selectArticle(article);
        // 判断查询结果是否为空
        if (list.isEmpty()) throw new ServiceException(StatusCode.ARTICLE_NOT_EXIST);//文章不存在
        return list;
    }


    /**
     * 业务层-文章详情查询
     * @param articleId
     * @return List<ArticleDetailsVO>
     */
    @Override
    public ArticleDetailsVO selectArticleDetails(Long articleId,Long userId,HttpSession session) {
        log.debug("业务层-文章详情查询: articleId={}", articleId);
        /* 查询文章 */
        Article article = new Article();
        article.setId(articleId);
        List<ArticleVO> list = articleMapper.selectArticle(article);
        // 判断文章是否存在
        if (list.isEmpty()) throw new ServiceException(StatusCode.ARTICLE_NOT_EXIST);//文章不存在

        /* 非作者与游客的文章浏览量增加 */
//        Long userId = (Long)session.getAttribute("user");
//        // 判断是否为当前用户是否为文章作者
//        if (!list.get(0).getUserId().equals(userId)){
//            articleMapper.updateArticleSkimNum(articleId);//增加浏览量
//        }
        articleMapper.updateArticleSkimNum(articleId);//增加浏览量

        // 查询文章具体内容并赋值给VO对象
        ArticleDetailsVO articleDetailsVO = articleDetailsMapper.selectArticleDetails(articleId);
        log.debug("业务层-文章详情查询-查询结果:{}", articleDetailsVO);
        BeanUtils.copyProperties(list.get(0), articleDetailsVO);//将文章内容赋值给VO对象
        // 查询点赞状态与收藏状态
        selectThumbsUpStatusAndFavoriteStatus(articleId, userId, articleDetailsVO);
        return articleDetailsVO;
    }
    private void selectThumbsUpStatusAndFavoriteStatus(Long articleId, Long userId, ArticleDetailsVO articleDetailsVO) {
        if (userId != null) {
            ThumbsUp thumbsUp = new ThumbsUp();
            thumbsUp.setUserId(userId);
            thumbsUp.setArticleId(articleId);
            ThumbsUp resultThumbsUp = thumbsUpMapper.selectThumbsUp(thumbsUp);
            if (resultThumbsUp != null) {
                articleDetailsVO.setThumbsUpStatus("1");
            }else {
                articleDetailsVO.setThumbsUpStatus("0");
            }
            FavoritesSaveParam favoritesSaveParam = new FavoritesSaveParam();
            favoritesSaveParam.setUserId(userId);
            favoritesSaveParam.setArticleId(articleId);
            Long resultFavoriteId = favoritesMapper.selectFavoritesArticleId(favoritesSaveParam);
            if (resultFavoriteId != null) {
                articleDetailsVO.setFavoriteStatus("1");
            }else {
                articleDetailsVO.setFavoriteStatus("0");
            }
        }
    }


    /**
     * 业务层-新增与更新文章
     * @param articleSaveParam
     */
    @Override
    public Long saveArticle(ArticleSaveParam articleSaveParam,HttpSession session) {
        log.debug("业务层-新增与更新文章: articleSaveParam={}", articleSaveParam);
        /* 用户是否登录校验 */
//        Long userId = LoginValidation.isLogin(session);

        /* 封装文章与文章内容对象 */
        Article article = new Article();
        BeanUtils.copyProperties(articleSaveParam, article);
        ArticleDetails articleDetails = new ArticleDetails();
        articleDetails.setContent(articleSaveParam.getContent());//设置文章内容

        LocalDateTime now = LocalDateTime.now();
        Long articleId = article.getId();
        /* 新增文章操作 */
        if (articleId == null){
            // 判断文章内容是否为空
            String content = articleDetails.getContent();
            if (content == null || content.trim().isEmpty()){
                throw new ServiceException(StatusCode.ARTICLE_NOT_EMPTY);//文章内容不能为空
            }
            /* 新增文章并创建审核单 */
            articleId = createArticle(article.getUserId(), article, articleDetails, now);
        }else {
            /* 修改文章操作 */
            updateArticle(articleId, article, articleDetails, now);
        }
        return articleId;
    }
    /**
     * 新增文章并创建审核单
     * @param userId
     * @param article
     * @param articleDetails
     * @param time
     * @return 文章ID
     */
    private Long createArticle(Long userId, Article article, ArticleDetails articleDetails, LocalDateTime time) {
        Long articleId;
        // 新增文章
        article.setUserId(userId);//通过session会话获取用户id
        article.setComment(0);//初始化总评数量
        article.setSkimNum(1);//初始化浏览量
        article.setLikesTotalNums(0);//初始化点赞总数
        article.setCreateTime(time);//初始化创建时间
        article.setAuditStatus(ArticleAuditStatusEnum.UN_AUDIT.getCode());//初始化文章审核状态--未审核
        articleMapper.insertArticle(article);

        // 新增文章内容
        articleId = article.getId();
        articleDetails.setArticleId(articleId);//设置文章id
        articleDetailsMapper.insertArticleDetails(articleDetails);

        // 创建文章审核单
        AuditInsertParam auditInsertParam = new AuditInsertParam();
        auditInsertParam.setArticleId(articleId);//设置文章id
        auditInsertParam.setAuditStatus(ArticleAuditStatusEnum.UN_AUDIT.getCode());//设置文章未审核状态-0
        auditInsertParam.setCreateTime(time);//设置创建时间
        auditMapper.insertAudit(auditInsertParam);
        return articleId;
    }
    /**
     * 更新文章操作
     * @param articleId
     * @param article
     * @param articleDetails
     * @param time
     */
    private void updateArticle(Long articleId, Article article, ArticleDetails articleDetails, LocalDateTime time) {
        /* 更新文章操作 */
        article.setUpdateTime(time);
        articleMapper.updateArticle(article);

        /* 判断文章内容是否修改 */
        ArticleDetailsVO aDVO = articleDetailsMapper.selectArticleDetails(articleId);
        if (aDVO.hashCode() != articleDetails.getContent().hashCode()){//文章内容hashcode比较
            articleDetails.setArticleId(articleId);//设置文章id
            articleDetailsMapper.updateArticleDetails(articleDetails);
        }
    }


    /**
     * 业务层-删除文章
     * @param articleId
     * @param session
     */
    @Override
    public void deleteArticle(Long articleId, HttpSession session) {
        log.debug("业务层-删除文章: articleId={}", articleId);
        /* 用户是否登录校验 */
//        Long userId = LoginValidation.isMyselfLogin(articleId, session);

        /* 查询文章是否属于当前用户 */
//        Article article = new Article();
//        article.setId(articleId);//设置文章id
//        List<ArticleVO> articleVOS = articleMapper.selectArticle(article);
//        if (!userId.equals(articleVOS.get(0).getUserId())){
//            throw new ServiceException(StatusCode.OPERATION_FAILED);//操作失败
//        }

        /* 删除文章操作 */
        articleMapper.deleteArticle(articleId);//删除文章
        articleDetailsMapper.deleteArticleDetails(articleId);//删除文章内容
    }
}
